package com.joysuch.wwyt.dataimport.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.zlg.common.util.CollectionUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.joysuch.wwyt.bp.entity.BpSystemVideo;
import com.joysuch.wwyt.bp.repository.BpSystemVideoDao;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.dataimport.service.ExcelExportService;
import com.joysuch.wwyt.dataperm.annotation.EnableDataPermission;
import com.joysuch.wwyt.edu.bean.WwytEduCertificateQueryParam;
import com.joysuch.wwyt.edu.bean.WwytEduCertificateUserVo;
import com.joysuch.wwyt.edu.service.WwytEduCertificateUserService;
import com.joysuch.wwyt.list.bean.BpListBizUploadWorkBean;
import com.joysuch.wwyt.list.bean.BpListBizWorkParamBean;
import com.joysuch.wwyt.list.bean.BpListBizWorkQueryBean;
import com.joysuch.wwyt.list.entity.BpListBizWork;
import com.joysuch.wwyt.list.service.BpListBizService;
import com.joysuch.wwyt.risk.bean.RiskPointEvaluationBean;
import com.joysuch.wwyt.risk.bean.RiskPointEvaluationDetailBean;
import com.joysuch.wwyt.risk.bean.RiskPointEvaluationItemBean;
import com.joysuch.wwyt.risk.entity.RiskPoint;
import com.joysuch.wwyt.risk.entity.RiskPointType;
import com.joysuch.wwyt.risk.repository.RiskDistrictDao;
import com.joysuch.wwyt.risk.repository.RiskPointDao;
import com.joysuch.wwyt.risk.repository.RiskPointTypeDao;
import com.joysuch.wwyt.risk.service.impl.RiskPointServiceImpl;
import com.joysuch.wwyt.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.SafeHtml;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ExcelExportServiceImpl implements ExcelExportService {

    @Autowired
    private RiskPointServiceImpl riskPointService;
    @Autowired
    private RiskPointDao riskPointDao;
    @Autowired
    private RiskDistrictDao riskDistrictDao;
    @Autowired
    private BpSystemVideoDao bpSystemVideoDao;
    @Autowired
    private RiskPointTypeDao riskPointTypeDao;
    @Autowired
    private WwytEduCertificateUserService wwytEduCertificateUserService;
    @Autowired
    private BpListBizService bpListBizService;

    /**
     * 获取打印数据
     *
     * @return
     */
    @Override
    public Map<String, Object> getDataMap(HttpServletRequest request, Integer flag) {
        if (flag == 0) {
            return getSafetyRisk();
        } else if (flag == 1) {
            return getHagard();
        } else if (flag == 2) {
            return getVideo();
        } else if (flag == 3) {
            return getCert(request);
        } else if (flag == 4) {
            return getListWork(request);
        } else {
            return null;
        }

    }

    //清单工作列表数据导出
    private Map<String, Object> getListWork(HttpServletRequest request) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String listCodeOrName = request.getParameter("listCodeOrName");
        String userCodeOrName = request.getParameter("userCodeOrName");
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        BpListBizWorkQueryBean queryBean = new BpListBizWorkQueryBean();
        queryBean.setListCodeOrName(listCodeOrName);
        queryBean.setUserCodeOrName(userCodeOrName);
        if (StringUtil.notEmpty(startDate)) {
            try {
                queryBean.setStartDate(DateUtil.beginOfDay(simpleDateFormat.parse(startDate)));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtil.notEmpty(endDate)) {
            try {
                queryBean.setEndDate(DateUtil.endOfDay(simpleDateFormat.parse(endDate)));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        List<BpListBizUploadWorkBean> all = bpListBizService.findPage(queryBean);
        //Excel数据
        Map<String, Object> map = new HashMap<>();

        List<Map<String, Object>> aList = all.stream().map(e -> {
            Map<String, Object> m = new HashMap<>();
            //清单编号
            m.put("listCode", e.getListCode());
            //清单名称
            m.put("listName", e.getListName());
            //工作名称
            m.put("workName", e.getWorkName());
            //工作内容
//            if (StringUtil.notEmpty(e.getContent())) {
//                m.put("content", e.getContent().substring(3, e.getContent().length() - 4));
//            } else {
            m.put("content", e.getContent());
//            }
            //状态
            m.put("stateName", e.getStateName());
            //上传人
            m.put("createByName", e.getCreateByName());
            //上传时间
            m.put("createByTime", simpleDateFormat.format(e.getCreateTime()));
            return m;
        }).collect(Collectors.toList());
        map.put("aList", aList);
        return map;
    }

    //持证管理数据导出
    private Map<String, Object> getCert(HttpServletRequest request) {
        //构造查询参数
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String nameOrCode = request.getParameter("nameOrCode");
        String certTypeId = request.getParameter("certTypeId");
        String certId = request.getParameter("certId");
        String effectQueryStartTime = request.getParameter("effectQueryStartTime");
        String effectQueryEndTime = request.getParameter("effectQueryEndTime");
        String reviewQueryStartTime = request.getParameter("reviewQueryStartTime");
        String reviewQueryEndTime = request.getParameter("reviewQueryEndTime");
        String certificateStatus = request.getParameter("certificateStatus");
        String userContractorFlag = request.getParameter("userContractorFlag");
        WwytEduCertificateQueryParam param = new WwytEduCertificateQueryParam();
        param.setPageSize(100);
        if (StringUtil.notEmpty(nameOrCode)) {
            param.setNameOrCode(nameOrCode);
        }

        if (StringUtils.isNotBlank(userContractorFlag)) {
            if (userContractorFlag.equals("1")) {
                param.setUserContractorFlag(Boolean.TRUE);
            } else {
                param.setUserContractorFlag(Boolean.FALSE);
            }
        }
        if (StringUtil.notEmpty(certTypeId)) {
            param.setCertTypeId(Long.parseLong(certTypeId));
        }
        if (StringUtil.notEmpty(certId)) {
            param.setCertId(Long.parseLong(certId));
        }
        if (StringUtil.notEmpty(effectQueryStartTime)) {
            try {
                param.setEffectQueryStartTime(simpleDateFormat.parse(effectQueryStartTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtil.notEmpty(effectQueryEndTime)) {
            try {
                param.setEffectQueryEndTime(simpleDateFormat.parse(effectQueryEndTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtil.notEmpty(reviewQueryStartTime)) {
            try {
                param.setReviewQueryStartTime(simpleDateFormat.parse(reviewQueryStartTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtil.notEmpty(reviewQueryEndTime)) {
            try {
                param.setReviewQueryEndTime(simpleDateFormat.parse(reviewQueryEndTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtil.notEmpty(certificateStatus)) {
            param.setCertificateStatus(Integer.parseInt(certificateStatus));
        }
        //go
        List<WwytEduCertificateUserVo> all = new ArrayList<>();
        int i = 0;
        for (; ; ) {
            param.setPageNum(i);
            ResultBean resultBean = wwytEduCertificateUserService.findPage(param);
//            Page<WwytEduCertificateUserVo> page = null;
            if (resultBean != null && resultBean.getData() != null) {
                List<WwytEduCertificateUserVo> data = (List<WwytEduCertificateUserVo>) resultBean.getData();
                if (CollectionUtils.isNotEmpty(data)) {
                    all.addAll(data);
                } else {
                    break;
                }
            } else {
                break;
            }
            i++;
        }
        //Excel数据
        Map<String, Object> map = new HashMap<>();

        List<Map<String, Object>> aList = all.stream().map(e -> {
            Map<String, Object> m = new HashMap<>();
            //工号
            m.put("userCode", e.getUserCode());
            //姓名
            m.put("userName", e.getUserName());
            //人员类型
            m.put("peopleType", e.getPeopleType());
            //所在部门
            m.put("departName", e.getDepartName());
            //岗位名称
            m.put("jobName", e.getJobName());
            //证书类型
            m.put("certificateTypeName", e.getCertificateTypeName());
            //证书名称
            m.put("certificateName", e.getCertificateName());


            //有效期开始时间
            if (e.getTakenTime() != null) {
                m.put("takenTime", simpleDateFormat.format(e.getTakenTime()));
            }
            //有效期结束时间
            if (e.getOutOfDateTime() != null) {
                m.put("outOfDateTime", simpleDateFormat.format(e.getOutOfDateTime()));
            }
            //复证日期
            if (e.getRepeatViewDateTime() != null) {
                m.put("repeatViewDateTime", simpleDateFormat.format(e.getRepeatViewDateTime()));
            }
            //发证机关
            m.put("licenseIssuingAgencies", e.getLicenseIssuingAgencies());
            //证件存放地
            m.put("licenseSavingArea", e.getLicenseSavingArea());
            //状态
            if (e.getCertificateStatus() != null) {
                switch (e.getCertificateStatus()) {
                    case 0:
                        m.put("certificateStatus", "草稿");
                        break;
                    case 1:
                        m.put("certificateStatus", "归档");
                        break;
                    case 2:
                        m.put("certificateStatus", "作废");
                        break;
                }
            }

            //备注
            m.put("remark", e.getRemark());
            return m;
        }).collect(Collectors.toList());
        map.put("aList", aList);
        return map;
    }

    //安全风险分级管控清单
    private Map<String, Object> getSafetyRisk() {
        //原始数据
        List<RiskPoint> all = riskPointDao.getTwoFormList();
        List<RiskPointEvaluationDetailBean> list = new ArrayList<>();
        for (RiskPoint p : all) {
            RiskPointEvaluationDetailBean evaluationDetail = riskPointService.queryEvaluationDetail(p);
            // 填写风险管控层级信息
            riskPointService.fillControlLevelInfo(p, evaluationDetail);
            // 兼容前端字段设计
            evaluationDetail.setLevel(p.getRiskLevel());
            list.add(evaluationDetail);
        }

        //Excel数据
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> aList = new ArrayList<>();
        for (RiskPointEvaluationDetailBean bean : list) {
            Map<String, Object> m = new HashMap<>();
            //风险点编号
            m.put("code", bean.getCode());
            //风险点名称
            m.put("name", bean.getName());
            //风险区域
            m.put("riskDistrictName", bean.getRiskDistrictName());
            //风险点类型
            m.put("riskTypeName", bean.getRiskTypeName());
            if (bean.getJha() != null) {
                //分析方法
                m.put("method", "作业危害分析(JHA)");
                m = putJhaOrSclData(m, bean.getJha(), "JHA");
            } else if (bean.getScl() != null) {
                RiskPointEvaluationBean reBean = bean.getScl();
                //分析方法
                m.put("method", "安全检查分析(SCL)");
                m = putJhaOrSclData(m, bean.getScl(), "SCL");
            } else {
                m.put("method", "未评估");
            }
            //风险级别
            m.put("levelName", bean.getLevelName());
            //管控层级
            m.put("controlLevel", bean.getControlLevel());
            //责任单位
            m.put("department", bean.getDepartment());
            //责任人
            m.put("person", bean.getPerson());
            aList.add(m);
        }
        map.put("aList", aList);
        return map;
    }

    //危害因素辨识排查清单
    @EnableDataPermission
    private Map<String, Object> getHagard() {
        //原始数据
        List<RiskPoint> all = riskPointDao.getTwoFormList();
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> alist = new ArrayList<>();
        for (RiskPoint point : all) {
            Map<String, Object> m = new HashMap<>();
            //风险的名称
            m.put("name", point.getName());
            //风险点类型
            RiskPointType type = riskPointTypeDao.findByCode(point.getType());
            if (type != null) {
                m.put("riskTypeName", type.getName());
            }
            // m.put("riskTypeName", RiskPointTypes.findNameByCode(point.getType()));
            //所属风险区域
            Long rId = riskPointDao.getRiskDistrictIdById(point.getId());
            if (rId != null) {
                m.put("riskDistrctName", riskDistrictDao.findNameById(rId));
            }
            //存在的主要危险(有害)因素
            m.put("unstandardSituationConsequence", point.getUnstandardSituationConsequence());
            //易发生的事故类型
            m.put("accidentType", point.getAccidentType());
            alist.add(m);
        }
        map.put("aList", alist);
        return map;
    }

    //组装jha或者scl相关数据
    private Map<String, Object> putJhaOrSclData(Map<String, Object> m, RiskPointEvaluationBean reBean, String type) {
        List<RiskPointEvaluationItemBean> items = reBean.getItems();
        StringBuilder identifyContent = new StringBuilder();
        StringBuilder controlMethodTech = new StringBuilder();
        StringBuilder controlMethodManage = new StringBuilder();
        StringBuilder controlMethodTrain = new StringBuilder();
        StringBuilder controlMethodProtect = new StringBuilder();
        StringBuilder controlMethodEmegency = new StringBuilder();
        for (RiskPointEvaluationItemBean itemBean : items) {
            if (StringUtils.isNotBlank(itemBean.getCheckItem())) {
                identifyContent.append("作业步骤:" + itemBean.getCheckItem()).append(",");
            }
            if (type.equals("JHA")) {
                if (StringUtils.isNotBlank(itemBean.getRiskSource())) {
                    identifyContent.append("风险源或潜在事件:" + itemBean.getRiskSource()).append(",");
                }
                if (StringUtils.isNotBlank(itemBean.getConsequence())) {
                    identifyContent.append("可能发生的事故类型及后果:" + itemBean.getConsequence()).append(";");
                }

            } else if (type.equals("SCL")) {
                if (StringUtils.isNotBlank(itemBean.getStandard())) {
                    identifyContent.append("标准:" + itemBean.getStandard()).append(",");
                }
                if (StringUtils.isNotBlank(itemBean.getConsequence())) {
                    identifyContent.append("不符合标准情况及后果:" + itemBean.getConsequence()).append(";");
                }
            }

            if (StringUtils.isNotBlank(itemBean.getControlMethodTech())) {
                controlMethodTech.append(itemBean.getControlMethodTech()).append(";");
            }

            if (StringUtils.isNotBlank(itemBean.getControlMethodManage())) {
                controlMethodManage.append(itemBean.getControlMethodManage()).append(";");
            }

            if (StringUtils.isNotBlank(itemBean.getControlMethodTrain())) {
                controlMethodTrain.append(itemBean.getControlMethodTrain()).append(";");
            }

            if (StringUtils.isNotBlank(itemBean.getControlMethodProtect())) {
                controlMethodProtect.append(itemBean.getControlMethodProtect()).append(";");
            }

            if (StringUtils.isNotBlank(itemBean.getControlMethodEmegency())) {
                controlMethodEmegency.append(itemBean.getControlMethodEmegency()).append(";");
            }
        }
        //辨识内容
        if (identifyContent.length() > 0) {
            m.put("identifyContent", identifyContent.deleteCharAt(identifyContent.length() - 1));
        }
        // 工程技术措施
        if (controlMethodTech.length() > 0) {
            m.put("controlMethodTech", controlMethodTech.deleteCharAt(controlMethodTech.length() - 1));
        }
        // 管理措施
        if (controlMethodManage.length() > 0) {
            m.put("controlMethodManage", controlMethodManage.deleteCharAt(controlMethodManage.length() - 1));
        }

        // 培训教育措施
        if (controlMethodTrain.length() > 0) {
            m.put("controlMethodTrain", controlMethodTrain.deleteCharAt(controlMethodTrain.length() - 1));
        }

        // 个体防护措施
        if (controlMethodProtect.length() > 0) {
            m.put("controlMethodProtect", controlMethodProtect.deleteCharAt(controlMethodProtect.length() - 1));
        }

        // 应急处置措施
        if (controlMethodEmegency.length() > 0) {
            m.put("controlMethodEmegency", controlMethodEmegency.deleteCharAt(controlMethodEmegency.length() - 1));
        }
        return m;
    }

    /**
     * 视频设备清单
     *
     * @return
     */
    private Map<String, Object> getVideo() {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> aList = new ArrayList<>();
        List<BpSystemVideo> list = bpSystemVideoDao.findAll();
        for (BpSystemVideo video : list) {
            Map<String, Object> m = new HashMap<>();
            //品牌
            m.put("brand", video.getBrand());
            //设备类型
            m.put("deviceType", video.getDeviceType());
            //名称
            m.put("name", video.getName());
            //账号
            m.put("account", video.getAccount());
            //密码
            m.put("password", video.getPassword());
            //ip
            m.put("ip", video.getIp());
            //端口号
            m.put("port", video.getPort());
            //通道号
            m.put("channelNo", video.getChannelNo());
            //风险区域
            if (video.getEvaluation() != null) {
                String riskDistrictName = riskDistrictDao.findNameById(new Long(video.getEvaluation()));
                m.put("riskDistrictName", riskDistrictName);
            }
            //实时视频流地址预览
            m.put("realTimeSite", video.getRealTimeSite());
            //历史视频流地址预览
            m.put("historySite", video.getHistorySite());
            //地址日期格式
            m.put("dateFormat", video.getDateFormat());
            //地址时间格式
            m.put("timeFormat", video.getTimeFormat());
            aList.add(m);
        }
        map.put("aList", aList);
        return map;
    }
}
